﻿using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace LatestVersionHandler.EventReceiver1
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class EventReceiver1 : SPItemEventReceiver
    {

        const string strVersion = "Current Version";
        const string strLatest = "Latest";
        const string delimiter = "_";

        /// <summary>
        /// An item is being updated
        /// </summary>
        public override void ItemUpdating(SPItemEventProperties properties)
        {
            //Check for proper fields "Current Version" and "Latest" and ensure "Current Version is populated"
            SPFieldCollection listFields = properties.List.Fields;
            if (listFields.ContainsField(strVersion) && listFields.ContainsField(strLatest) && properties.ListItem != null && properties.ListItem[strVersion] != null)
            {
                float maxVersion = (float)properties.ListItem[strVersion];

                //Parse prior documents by the same name (up to last underscore), setting all to false(No)
                string titleMatch = properties.ListItem.Title.Remove(properties.ListItem.Title.LastIndexOf(delimiter));

                // Build a query.  Where title is an exact match or is a match with a delimiter.
                SPQuery query = new SPQuery();
                query.Query =
                 "<Where><Or>" +
                     "<BeginsWith>" +
                         "<FieldRef Name='Title'/>" +
                         "<Value Type='text'>" + titleMatch + delimiter + "</Value>" +
                     "</BeginsWith>" +
                     "<Eq>" +
                         "<FieldRef Name='Title'/>" +
                         "<Value Type='text'>" + titleMatch + "</Value>" +
                     "</Eq>" +
                 "</Or></Where>" +
                 "<OrderBy>" +
                     "<FieldRef Name='" + strVersion + "' Ascending='False' />" +
                 "</OrderBy>";
                SPListItemCollection listItems = properties.List.GetItems(query);
                foreach (SPListItem item in listItems)
                {
                    //Check that version is not null 
                    if (item[strVersion] != null)
                    {
                        //Only update if different
                        if (item[strLatest] == null || (bool)item[strLatest] != (float)item[strVersion] > maxVersion)
                        {
                            item[strLatest] = (float)item[strVersion] > maxVersion;
                            item.SystemUpdate(false);
                            if ((bool)item[strLatest])
                            {
                                maxVersion = (float)item[strVersion];
                                properties.ListItem[strLatest] = false;
                            }
                        }
                    }
                }
            }

            //Run default code
            base.ItemUpdating(properties);
        }
    }
}
